package com.le.edu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.le.edu.domain.entity.BaseEntity;
import com.le.edu.domain.entity.Comment;
import com.le.edu.domain.vo.CommentVO;
import com.le.edu.mapper.CommentMapper;
import com.le.edu.service.CommentService;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;

/**
 * @author 17447
 * @description 针对表【t_comment】的数据库操作Service实现
 * @createDate 2024-04-21 12:39:15
 */
@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment>
        implements CommentService {

    @Override
    public List<CommentVO> updateCommentTreeList(Long courseId) {
        List<CommentVO> allCommentVO = baseMapper.selectListWhitUser(new QueryWrapper<Comment>()
                .eq("c.course_id", courseId)
                .eq("c.del_flag", "0"));
        List<CommentVO> commentTree = allCommentVO.stream().filter(c -> c.getPid().equals(0L))
                .peek(c -> c.setChildren(getChildren(c, allCommentVO)))
                .sorted(Comparator.comparing(BaseEntity::getCreateTime))
                .toList();
        return commentTree;
    }

    /**
     * 递归获取评论树
     *
     * @param commentVO
     * @param all
     * @return
     */
    private List<CommentVO> getChildren(CommentVO commentVO, List<CommentVO> all) {
        return all.stream()
                .filter(c -> c.getPid().equals(commentVO.getCommentId()))
                .peek(c -> c.setChildren(getChildren(c, all)))
                .sorted(Comparator.comparing(BaseEntity::getCreateTime))
                .toList();
    }
}




